package org.edunext.selenide;

import com.codeborne.selenide.Configuration;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;

import java.util.Properties;

import static com.codeborne.selenide.Condition.exist;
import static com.codeborne.selenide.Selectors.byTagName;
import static com.codeborne.selenide.Selectors.byXpath;
import static com.codeborne.selenide.Selenide.$;
import static com.codeborne.selenide.Selenide.open;

public class WebFastSelenideDriverJUnitRunner extends BlockJUnit4ClassRunner {

    private static final String CHROME_WEB_DRIVER_KEY = "webdriver.chrome.driver";

    private Properties settings;

    public WebFastSelenideDriverJUnitRunner(Class<?> testClass) throws InitializationError {
        super(testClass);
        settings = SimplePropertiesUtil.loadProperties("selenide4webfast.properties");
        Configuration.baseUrl = settings.getProperty("webfast.baseUrl");
        System.setProperty(CHROME_WEB_DRIVER_KEY,
                settings.getProperty(CHROME_WEB_DRIVER_KEY));
    }

    @Override
    protected Statement withBeforeClasses(Statement statement) {
        if ("true".equals(settings.getProperty("webfast.login.enabled"))) {
            open("/login");
            if (isNotLogin()) {
                login();
            }
        }
        return super.withBeforeClasses(statement);
    }

    private boolean isNotLogin() {
        return $(byXpath("//a[text()='登录']")).exists() &&
                $(byXpath("//a[text()='注册']")).exists();
    }

    private void login() {
        $("#login_username").setValue(settings.getProperty("webfast.username"));
        $("#login_password").setValue(settings.getProperty("webfast.password"));
        $(byXpath("//button[text()='登录']")).click();
        $(byXpath("//span[text()='私信']")).shouldHave(exist);
        $(byXpath("//span[text()='通知']")).shouldHave(exist);
    }
}
